package JZ_Offer.dataStructure.list;

import base.ListNode;

import java.util.ArrayList;

/**
 * @Author piper
 * @Date 2019/11/6 10:55 上午
 */
public class JZ6_从尾到头打印链表 {

    /**
     * 调用add方法，放到第一位，看似代码很简单
     * 其实放到第一位之后后面每位都要往后移动
     */
    static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        while (listNode != null) {
            list.add(0, listNode.val);
            listNode = listNode.next;
        }
        return list;
    }

    /**
     * arraylist本质也是个数组，我将第一位和最后一位换一下位置不就行了吗
     */
    static ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(listNode.val);
        while (listNode.next != null) {
            listNode = listNode.next;
            arrayList.add(listNode.val);
        }

        int l = 0, r = arrayList.size() - 1, m = (r + l) / 2;
        while (l <= m) {
            int a = arrayList.get(l);
            arrayList.set(l, arrayList.get(r));
            arrayList.set(r, a);
            l++;
            r--;
        }
        return arrayList;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;
        System.out.println(printListFromTailToHead1(l1));
    }

}
